package com.zhongxi.guoyuan.view.personalCenter;

import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.center.UserCenterResult;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasCompleteFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasDealFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasNoApplyFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasNoDealFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.update.UpdateActivity;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class BeautifulStoreOrderActivity extends BaseActivity implements View.OnClickListener {

    //地图导航
    private static final String APP_FOLDER_NAME = "";
    private String mSDCardPath = null;
    public static List<Activity> activityList = new LinkedList<Activity>();
    private int currentIndex, index;

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }

    };
    private RelativeLayout relaContainer;
    private Button[] tabs;
    private StoreOrderHasNoApplyFragment noPayFragment;
    private StoreOrderHasNoDealFragment noDealFragment;
    private StoreOrderHasDealFragment dealFragment;
    private StoreOrderHasCompleteFragment completeFragment;
    private Fragment[] fragments;
    private TextView tvUpdate;
    private TextView tvUserName;
    private TextView tvUserPhone;
    private ImageView ivUserHead;
    private TextView tvBonusPoint;
    private TextView tvIdentify;
    private ImageView ivBox;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_beautiful_store_order);
        initTitle();
        tvTitle.setText("美币预约列表");
        initPageView();

        tvUpdate = (TextView) findViewById(R.id.tvUpdate);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvUserPhone = (TextView) findViewById(R.id.tvUserPhone);
        ivUserHead = (ImageView) findViewById(R.id.ivUserHead);
        tvBonusPoint = (TextView) findViewById(R.id.tvBonusPoint);
        tvIdentify = (TextView) findViewById(R.id.tvIdentify);

        ivBox = (ImageView) findViewById(R.id.ivBox);

        mapNavi();//初始化百度地图
    }

    private void mapNavi() {
        activityList.add(this);
        if (initDirs()) {
            initNavi();
        }
    }

    /**
     * 获取目录
     *
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    String authinfo = null;

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                BeautifulStoreOrderActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        }, null, ttsHandler, ttsPlayStateListener);

    }

    private void initSetting() {
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    private void initPageView() {

        relaContainer = (RelativeLayout) findViewById(R.id.relaContainer);
        tabs = new Button[4];
        tabs[0] = (Button) findViewById(R.id.tab0);
        tabs[1] = (Button) findViewById(R.id.tab1);
        tabs[2] = (Button) findViewById(R.id.tab2);
        tabs[3] = (Button) findViewById(R.id.tab3);
        tabs[0].setSelected(true);

        noPayFragment = new StoreOrderHasNoApplyFragment();
        noDealFragment = new StoreOrderHasNoDealFragment();
        dealFragment = new StoreOrderHasDealFragment();
        completeFragment = new StoreOrderHasCompleteFragment();
        fragments = new Fragment[]{noPayFragment, noDealFragment, dealFragment, completeFragment};

        getSupportFragmentManager().beginTransaction()
                .add(R.id.relaContainer, noPayFragment)
                .hide(noDealFragment).commit();

    }

    @Override
    protected void initData() {
        super.initData();
        getServer(Url.USER_CENTER, null, "", false, null, "get");
    }

    private void initViewData(UserCenterResult result) {
        try{
            if(null!=result.getUserInfo().getShopname()&&!"".equals(result.getUserInfo().getShopname())){
                tvUserName.setText(result.getUserInfo().getShopname());
            }else{
                tvUserName.setText(R.string.app_name);
            }
            if(null!=MyApplication.getInstance().getPhone()&&!"".equals(MyApplication.getInstance().getPhone())){
                tvUserPhone.setText(MyApplication.getInstance().parseSecutiryKey(result.getUserInfo().getMphone()));
            }else{
                tvUserPhone.setText("");
            }
            int point = 0;
            if (null != result.getRights() && result.getRights().size() > 0) {
                for (int i = 0; i < result.getRights().size(); i++) {
                    if (null != String.valueOf(result.getRights().get(i).getUsertype())) {
                        if (result.getRights().get(i).getUsertype() == 0) {  //股东
                            if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                                point += result.getRights().get(i).getSharesnum();
                        } else {                                                            //权益会员
                            if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                                point += result.getRights().get(i).getSharesnum();
                        }
                    }
                }
            }
            if (null != String.valueOf(point)) {
                tvBonusPoint.setText(String.valueOf(point));
            }else {
                tvBonusPoint.setText("0");
            }
            if(null!=result.getUserInfo().getAvatar()&&!"".equals(result.getUserInfo().getAvatar())){
                Glide.with(context).load(Url.BASE_URL+result.getUserInfo().getAvatar()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivUserHead);
            }
            String sb = new String();
            if(null!=result.getUserInfo().getIsprivilege()){
                if("1".equals(result.getUserInfo().getIsprivilege())){
                    sb+="权益会员";
                    tvUpdate.setVisibility(View.GONE);
                }
            }
            if(null!=sb&&!"".equals(sb)){
                tvIdentify.setText(sb.toString());
            }else{
                tvIdentify.setText("普通会员");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try {
            Gson gson = new Gson();
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        Log.i("base", response);
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            UserCenterResult result = gson.fromJson(response, UserCenterResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            initViewData(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tabs[0].setOnClickListener(this);
        tabs[1].setOnClickListener(this);
        tabs[2].setOnClickListener(this);
        tabs[3].setOnClickListener(this);
        ivBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BoxActivity.class);
                intent.putExtra("index", 1);
                startActivity(intent);
            }
        });
        tvUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(UpdateActivity.class);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tab0:
                index = 0;
                break;
            case R.id.tab1:
                index = 1;
                break;
            case R.id.tab2:
                index = 2;
                break;
            case R.id.tab3:
                index = 3;
                break;
        }
        if(currentIndex != index){
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentIndex]);
            if(!fragments[index].isAdded()){
                trx.add(R.id.relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        tabs[currentIndex].setSelected(false);
        tabs[index].setSelected(true);
        currentIndex = index;
    }

}